package com.example.sqlitedemo.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


import java.util.ArrayList;
import java.util.List;

public class DBService {
    private MyHelper myHelper;
    private SQLiteDatabase db;

    /**
     * 打开数据库
     *
     * @param context
     */
    public DBService(Context context) {
        if (db == null) {
            myHelper = new MyHelper(context);
            db = myHelper.getWritableDatabase();
        }
    }

    /**
     * 关闭数据库
     */
    public void closeDB() {
        if (db != null) {
            db.close();
        }
    }

    /**
     * 添加商品信息
     *
     * @param product
     */
    public void insert(Product product) {
        try {
            ContentValues cv = new ContentValues();
            cv.put("productName", product.getProductName());
            cv.put("price", product.getPrice());
            db.insert("product", null, cv);
            Log.i("db", "insert: 插入数据成功！");
        } catch (Exception e) {
            Log.i("db", "insert: 插入数据失败！");
        }
    }

    /**
     * 根据商品编号pid修改商品信息
     *
     * @param product
     */
    public void updatePrice(Product product) {
        ContentValues cv = new ContentValues();
        cv.put("price", product.getPrice());
        int i = db.update("product", cv, "pid=?", new String[]{String.valueOf(product.getPid())});
        if (i > 0) {
            Log.i("db", "update: 更新数据成功！");
        } else {
            Log.i("db", "update: 更新数据失败！");
        }
    }

    /**
     * 根据商品编号pid删除商品
     * @param pid
     * @return
     */
    public int deletProduct(int pid) {
        int i = db.delete("product", "pid=?", new String[]{String.valueOf(pid)});
        if (i > 0) {
            Log.i("db", "delete: 删除数据成功！");
        } else {
            Log.i("db", "delete: 删除数据失败！");
        }
        return i;
    }

    /**
     * 查询所有商品信息
     * @return
     */
    public List<Product> findAll() {

        List<Product> list = new ArrayList<>();
        Cursor cursor = db.query("product", null, null, null, null,
                null, null);
        while (cursor.moveToNext()) {
            Product product = new Product();
            product.setPid(cursor.getInt(cursor.getColumnIndex("pid")));
            product.setProductName(cursor.getString(cursor.getColumnIndex("productName")));
            product.setPrice(cursor.getDouble(cursor.getColumnIndex("price")));
            list.add(product);
        }
        return list;
    }
}
